package org.dtrd.base;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.common.api.dto.BasePageRequest;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.util.CheckUtil;
import org.dtrd.common.util.DateUtils;
import org.dtrd.config.system.Constant;
import org.dtrd.config.system.SystemState;
import org.dtrd.modules.record.entity.request.TimePeriodRequest;
import org.dtrd.modules.record.util.TimePeriod;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author 萧
 * @date:2021-08-26 9:02 上午
 **/
@Slf4j
public class BaseController {

    protected Result error(SystemState.ResponseState response) {
        return Result.error(response.getCode(), response.getMsg());
    }

    protected Integer getPageSize(Integer param, Integer defaultValue) {
        param = getParam(param, defaultValue);
        if (param < 1) {
            param = defaultValue;
        }
        return param;
    }

    protected Integer getIntParam(Integer param, Integer defaultValue) {
        return getParam(param, defaultValue);
    }

    protected String getStringParam(String param, String defaultValue) {
        return getParam(param, defaultValue);
    }

    protected Double getDoubleParam(Double param, Double defaultValue) {
        return getParam(param, defaultValue);
    }

    private <T> T getParam(T param, T defaultValue) {
        if (param == null) {
            param = defaultValue;
        }
        return param;
    }

    protected boolean isIntParamInvalid(Integer value) {
        return value == null || value < 1;
    }

    /**
     * 处理请求时间
     *
     * @param inputMap
     * @return
     */
    protected String[] handleTimePeriod(TimePeriodRequest inputMap) {
        String[] timePeriod = new String[2];
        String startDate = null;
        String endDate = null;
//        0、2直接获取参数值，3 以当天为结束日期按照指定周期倒推开始时间
        int type = inputMap.getType() == null ? 3 : inputMap.getType();
        if (type == 0 || type == 2) {
            startDate = inputMap.getStartTime();
            endDate = inputMap.getEndTime();
            if (CheckUtil.isEmpty(endDate)) {
                endDate = startDate;
            }
//            // 最长周期3个月，大于3个月取开始时间往后3个月时间
//            String limitDate = DateUtils.getNextQuarterToday(startDate);
//            if (limitDate.compareTo(endDate) < 0) {
//                endDate = limitDate;
//            }
        } else if (type == 3) {
            // 按照周期查询 0：全部 1：一周、2：两周、3：一月、4：两月 5 三月 6 半年 7 一年
            endDate = DateUtils.getDate(DateUtils.date_sdf.get().toPattern());
            int period = inputMap.getPeriod();
            TimePeriod timePeriodType = TimePeriod.valueOf(period);
            int dateSub = timePeriodType.getDuration();
            if (dateSub == Integer.MIN_VALUE) {
                startDate = "1970-01-01";
            } else {
                startDate = DateUtils.dateAdd(dateSub);
            }
        }
        timePeriod[0] = startDate;
        timePeriod[1] = endDate;
        return timePeriod;
    }

    protected String[] handleTimePeriod(int type, int period, String startDate, String endDate) {
        String[] timePeriod = new String[2];
//        0、2直接获取参数值，3 以当天为结束日期按照指定周期倒推开始时间
        if (type == 0 || type == 2) {
            if (CheckUtil.isEmpty(endDate)) {
                endDate = startDate;
            }
        } else if (type == 3) {
            // 按照周期查询 0：全部 1：一周、2：两周、3：一月、4：两月 5 三月 6 半年 7 一年
            endDate = DateUtils.getDate(DateUtils.date_sdf.get().toPattern());
            TimePeriod timePeriodType = TimePeriod.valueOf(period);
            int dateSub = timePeriodType.getDuration();
            if (dateSub == Integer.MIN_VALUE) {
                startDate = "1970-01-01";
            } else {
                startDate = DateUtils.dateAdd(dateSub);
            }
        }
        timePeriod[0] = startDate;
        timePeriod[1] = endDate;
        return timePeriod;
    }

    protected JSONObject getJSONParams(HttpServletRequest request) {
        JSONObject jsonParam = null;
        try {
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(
                    request.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            log.info("BaseController.getJSONParams.[request] " + sb);
            jsonParam = JSONObject.parseObject(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonParam;
    }

    protected String getParamsAsString(HttpServletRequest request) {
        try {
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(
                    request.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            log.info("BaseController.getParamsAsString.[request]" + sb);
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void handlePageRequest(BasePageRequest request) {
        Integer pageNum = request.getPageNum();
        Integer pageSize = request.getPageSize();
        pageNum = getIntParam(pageNum, 1);
        pageSize = getPageSize(pageSize, Constant.PAGESIZE);
        request.setPageNum(pageNum);
        request.setPageSize(pageSize);
    }

    protected int setTotalPage(int pageSize, int count) {
        int totalPage = count / pageSize;
        return count % pageSize == 0 ? totalPage : totalPage + 1;
    }

    protected <T> JSONObject wrapperPage(IPage<T> page) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("recordList", page.getRecords());
        jsonObject.put("totalPage", page.getPages());
        jsonObject.put("count", page.getTotal());
        return jsonObject;
    }
}
